package com.atguigu.gulimall.order.config;

import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.AbstractMessageConverter;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.annotation.PostConstruct;

@Configuration
public class MyRabbitMqConfig {



    @Bean
   public AbstractMessageConverter messageConverter(){
      return new Jackson2JsonMessageConverter();
    }

    /**
     * 消息回调
     */

    @Bean
    public RabbitTemplate initRabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate=new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setMessageConverter(messageConverter());
    /*    rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean b, String s) {
                System.out.println("confirm...correlationData["+correlationData+"]==>ack:["+b+"]==>cause:["+s+"]");
            }
        });*/

        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
            @Override
            public void returnedMessage(ReturnedMessage returnedMessage) {
                System.out.println("Fail Message["+returnedMessage.getMessage()+"]==>replyCode["+returnedMessage.getReplyCode()+"]" +
                        "==>replyText["+returnedMessage.getReplyText()+"]==>exchange["+returnedMessage.getExchange()+"]==>routingKey["+returnedMessage.getRoutingKey()+"]");
            }
        });
        return rabbitTemplate;
    }
}
